package OnlineExam.login;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import OnlineExam.*;
import OnlineExam.db.*;
import registration.*;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;


/**
 *  Authorize a user and redirect to the respective page.
 */


public final class HomeAction extends Action 
{
		
   	 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, 
					 HttpServletResponse response)
	 {
    
		HttpSession session = request.getSession(); 
        HomeForm f = (HomeForm) form;

        String username = f.getUsername ();
		String password = f.getPassword ();

		User u = authorizeUser (username, password);
		if (u == null)
        	return (mapping.findForward("failure"));

		session.setAttribute ("USER", u);

		List<Category> adminCategories = u.retrieveAdminCategories();

		if (adminCategories.size() > 0)
        	return (mapping.findForward("catadmin"));
		else
        	return (mapping.findForward("user"));
	 }

	 /**
	 *  
	 *  authorizes a user and returns user object if user present else return null.
	 */
		

	public User authorizeUser(String user, String pass)
	{
		try 
		{
			List list = DBUtil.select ("User", "registration.HibernateUser", "EmailId", user, "Password", pass, "Status", "confirmed");
			if (list.size() == 0)
				return null;
			else 
				return (User)list.listIterator().next();
		}
		catch (DBException e)
		{
			System.out.println ("HibernateException in HomeAction " + e);
			return null;
		}
	}
}
